﻿/**
* @author Alexander Rindo
* @project Flashview
* @version 0.4
* @purpose Loads and parses XML
**/

package com.alexrindo.flashview.xml
{
	import com.alexrindo.flashview.data.GalleryData;
	import flash.events.*
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class XMLParser extends EventDispatcher
	{
		private var _data:GalleryData
		
		private var _xml:XML
		private var _xmlLoader:URLLoader
		
		public const PARSE_COMPLETE:String = "parse_complete"
		
		public function processXMLData(URL:String):void
		{
			_xmlLoader = new URLLoader()
			_xmlLoader.addEventListener(Event.COMPLETE, parseXML, false, 0, true)
			_xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, errorXML, false, 0, true)
			_xmlLoader.load(new URLRequest(URL))
		}
		
		private function parseXML(e:Event):void
		{
			_xml = new XML(e.target.data)
			
			_data = GalleryData.getInstance()
			_data.baseURL = _xml.config.base_URL
			_data.galleryName = _xml.config.gallery_name
			_data.imageFolderURL = _xml.config.gallery_folder
			_data.thumbnailFolderURL = _xml.config.thumb_folder
			_data.slideShowTime = _xml.config.slideshow_timer
			_data.pictureCount = _xml.images.image.length()
			
			if (_xml.config.protect_pictures == "false")
			{
				_data.protectImages = false
			} else {
				_data.protectImages = true
			}
			
			for (var i:int = 0; i < _data.pictureCount; i++) 
			{
				if (_xml.images.image[i].@url != undefined)
				{
					_data.setImageURL(String(_xml.images.image[i].@url), i)
					_data.setType(String(_xml.images.image[i].@url.split(".")[1]),i)
				}
				if (_xml.images.image[i].@caption != undefined)
				{
					_data.setCaption(String(_xml.images.image[i].@caption),i)
				}
				if (_xml.images.image[i].@caption != undefined)
				{
					_data.setName(String(_xml.images.image[i].@name),i)
				}
				
			}
			dispatchEvent(new Event(PARSE_COMPLETE))
		}
		
		private function errorXML (e:IOErrorEvent):void
		{
			trace("No XML Data file found, please create a new XML file or find the original.")
			trace(e.text)
		}
	}
}


